import {
  getPostsService,
  getPostService,
  postPostService,
  patchPostService,
  deletePostService,
} from '../service/index.js'

export const getPosts = async ctx => {
  try {
    const query = ctx.query
    const title = ctx.query.title || ''
    const pagenum = Math.abs(Number(query.pagenum)) || 1
    const pagesize = Math.abs(Number(query.pagesize)) || 10
    const skip = (pagenum - 1) * pagesize
    const posts = await getPostsService(title, skip, pagesize)
    ctx.body = {
      data: posts,
      message: posts.length > 0 ? '获取帖子成功' : '帖子列表为空',
    }
  } catch (err) {
    throw err
  }
}

export const getPost = async ctx => {
  try {
    const id = parseInt(ctx.params.id)
    const post = await getPostService(id)
    ctx.body = {
      data: post,
      message: post ? '获取帖子成功' : '此帖子不存在',
    }
  } catch (err) {
    throw err
  }
}

export const postPost = async ctx => {
  try {
    const { title, content, topicId } = ctx.request.body
    const post = await postPostService({
      title,
      content,
      topicId: parseInt(topicId),
    })
    ctx.body = {
      data: post,
      message: '创建帖子成功',
    }
  } catch (err) {
    throw err
  }
}

export const patchPost = async ctx => {
  try {
    const id = parseInt(ctx.params.id)
    const { title, content, topicId } = ctx.request.body
    const post = await patchPostService(id, {
      title,
      content,
      topicId: parseInt(topicId),
    })
    ctx.body = {
      data: post,
      message: '更新帖子成功',
    }
  } catch (err) {
    throw err
  }
}

export const deletePost = async ctx => {
  try {
    const id = parseInt(ctx.params.id)
    const post = await deletePostService(id)
    ctx.body = {
      message: post.count === 1 ? '删除帖子成功' : '此帖子不存在',
    }
  } catch (err) {
    throw err
  }
}
